<template>
    <div>
        <div class="pc_head">
            <span class="click_select">模版名称</span>
            <div class="head_btn">
				<span @click="takeScreenshot"><i class="el-icon-camera-solid"></i>获取</span>
                <span><i class="el-icon-camera-solid"></i>预览</span>
                <span @click="dialogVisible = true,formData = {}"><i class="el-icon-s-finance"></i>保存</span>
            </div>
        </div>
		
        <div class="pc_main">
			
			<!-- <div class="pc_left">
				<vue-scroll :ops="ops" style="width:100%;height:calc(100vh - (100vh-60px))">
    			<el-menu
    			  default-active="2"
    			  class="el-menu-vertical-demo"
    			>
				<el-submenu v-for="(item,index) in canvas" :key="index" :index="item.no" >
        		  	<template slot="title" >
					  <span style="font-weight: 600;">{{item.name}}</span>
					</template>
        		  	<el-menu-item v-for="(val,i) in item.children" :key="i" :index="val.no">{{val.name}}</el-menu-item>
        		</el-submenu>
    			</el-menu>
				</vue-scroll>
			</div> -->

			<vue-scroll :ops="ops" style="width:100%;height:calc(100vh - 60px)">
				<div class="doc_canvas_box">
					<div class="doc_canvas_subline"  @click="delAllDrag"></div>
					<div class="doc_canvas_cont">
						<!-- <div class="canvas_dom_box">
							<img  src="../../assets/image/compatibility/1.png" alt="">
						</div> -->
					</div>
				</div>
			</vue-scroll>
            <leftPage ></leftPage>
            <rightPage @itemBtnsI="itemBtnsI" @end="end" ></rightPage>
        </div>

		 <div style='z-index: 9999;' class="menu"> 
			 <div @click="rightTop" class=''>置于顶层</div>
			 <div @click="rightDown" class=''>置于底层</div>
			<div @click="rightDel" class='del'>删除</div>
		</div>

        <el-dialog
		  title="新增程序"
		  :visible.sync="dialogVisible"
		  width="35%"
		  class="equip">
		  <formTemplate :formSet="formSet" :optionData='optionData' :postData="formData" :rules='rules' :isDialog="true" @flag="save" @close="close"></formTemplate>
		</el-dialog>
		
    </div>
</template>

<script>
// import html2canvas from 'html2canvas'; //截屏工具
import Bus from '@/utils/bus.js'
import leftPage from './left'
import rightPage from './right'
import formTemplate from '@/components/form.vue'
export default {
    components: {
		leftPage,
		rightPage,
        formTemplate
	},
    data() {
	    return {
			canvas:[
				{
					name:'组态一',
					no:'1',
					children:[
						{name:'画布1-1',no:"1-1"},
						{name:'画布1-2',no:"1-2"},]
				},
				{
					name:'组态二',
					no:'2',
					children:[
						{name:'画布2-1',no:'2-1'},]
				},
			],
			endData:{
				left:0,
				top:0
			},
			delDom:'',
			isitemBtnsI:'1',
			ops: {
				vuescroll: {},
				scrollPanel: {},
				rail: {
					keepShow: true
				},
				bar: {
					hoverStyle: true,
					onlyShowBarOnScroll: false, //是否只有滚动的时候才显示滚动条
					background: "#D6D8DD", //滚动条颜色
					opacity: 0.9, //滚动条透明度
					"overflow-x": "hidden",
				}
			},
            dialogVisible:false,
            formSet:[
				{ span: 24, label: '编号：', prop: 'number', type: 'input', disabled:false,width:'85%'},
                { span: 24, label: '程序名称：', prop: 'programName', type: 'input' , disabled:false,width:'85%'},
                { span: 24, label: '程序类型：', prop: 'type', type: 'select', disabled:false ,width:'85%'},
                { span: 24, label: '描述：', prop: 'describes', type: 'input', disabled:false ,width:'85%'},
                { span: 24, label: '图板图标：', prop: 'iconId', type: 'select_img', disabled:false ,width:'85%'},
			],
            rules: {
        	    number: { required: true, message: '不能为空', trigger: 'blur' },
        	    programName: { required: true, message: '不能为空', trigger: 'blur' },
        	    describes: { required: true, message: '不能为空', trigger: 'blur' },
        	    // iconId: { required: true, message: '不能为空', trigger: 'blur' },   
                type: { required: true, message: '不能为空', trigger: 'blur' },      
        	}, 
            optionData:{
				iconId:[],
                type:[{name:'气象物联',value:'1'},{name:'智能水肥',value:'2'},{name:'智能安防',value:'3'}]
			},
            formData:{},
			isdown:false,//是否旋转
			maxZ:1,
			minZ:-1,
        }
    },
    created(){
		
    },
	mounted() {
		let that = this
		var oldY= null;
        // var isdown = false;

		$('.doc_canvas_cont').on('mousedown','.xzIcon',function(e){
			let w = $(this).parent().css('width').split('px').join('')
			let h = $(this).parent().css('height').split('px').join('')
			w = Number(h)
			h = Number(h)
			// $(this).parent().removeClass('selected_dom')
			// $(this).after('<div class="bor" style="border: 3px solid #24B14E;opacity:0.1;z-index: 3000;"></div>');
			// $(".bor").css({"width":w,"height":h+30+'px',"position": "absolute","top": "-25px"})
			
			if($(this).parent().text() != ''){
				let parent = $(this).parent().attr('id').substring(0,9)
				if(parent == '0function' || parent == '1function' ){ //时间旋转按钮
					$(this).css({"width":w*5+'px',"height":h*4+'px','opacity':'0.1',"position": "absolute","left": "23%"})
				}else if(parent == '2function'){ //天气旋转按钮
					$(this).css({"width":w*1.2+'px',"height":h*1.5+'px','opacity':'0',"position": "absolute","left": "-20%"})
				}else{ //文本旋转按钮
					$(this).css({"width":w+(w/2)+'px',"height":h+30+'px','opacity':'0.1',"position": "absolute","left": "23%"})
				}
			}else{
				$(this).css({"width":w+20+'px',"height":h+20+'px','opacity':'0',"position": "absolute","left": "-10px"})
			}
      		const element = e.target;
      		const rect = element.getBoundingClientRect();
      		element.dataset.centerX = rect.left + rect.width / 2;
      		element.dataset.centerY = rect.top + rect.height / 2;
      		element.dataset.angle = that.getDragAngle(e);
            that.isdown = true;
            oldY = e.clientY;
			console.log(oldY,'down');

			return false
        });
		$('.doc_canvas_cont').on('mousemove','.xzIcon',function(e){ 
			e.stopPropagation(); 
            if(that.isdown){
				//清除拖拽和遗留的克隆效果
				// $(this).parent().resizable({disabled: true })
				$(this).parent().draggable({   
        	    activeClass: "ui-state-hover",
        	    hoverClass: "ui-state-active",
				disabled:true,
        	    start: function (event, ui) {
        	        $(ui.helper).remove(); //destroy clone
        	        $(ui.draggable).remove(); //remove from list    
        	    }
        	});
				 var angle = that.getDragAngle(e);
        		// e.target.style.transform = 'rotate(' + angle + 'rad)';
        		// e.target.offsetParent.style.transform = 'rotate(' + angle + 'rad)';
                $(this).parent().css("transform","rotate("+angle+"rad)");
            }
			
			return false
        });
		$('.doc_canvas_cont').on('mouseup','.xzIcon',function(e){
			// $(this).attr("src",require("./xuanzhuan.png"));
			$(this).css({"width":'16px',"height":'16px','opacity':'1',"position": "absolute","left": "50%"})
			// $(".bor").remove()
			e.target.dataset.angle = that.getDragAngle(e);
            oldY = null;
			that.isdown = false;
        });
		
		$('.doc_canvas_cont').on('mousemove','.svgBody',function(){
			if(that.isitemBtnsI == '1' && that.isdown === false && $(this).parent().attr('class') == 'doc_canvas_cont'){	
				// console.log('svgBody');
				$(this).draggable({
        		  cursor: 'move',
        		  disabled:false,
        		  helper: "clone",
				start:function(e,ui){
				},
        		// drag: function (event, ui) { console.log("拖拽中"); },
        		stop: function (e,ui) { 
					if(that.isdown === false){
						console.log(that.isdown,"拖拽结束"); 
						$('.doc_canvas_cont').children(".svgBody").resizable({disabled: true }).removeClass('selected_dom')
        		    	$('.doc_canvas_cont').children(".svgBody").children(".ui-resizable-handle").css("display", "none");
						$(".xzIcon").css("visibility","hidden");
        		    	  let dom = $(e.target)[0]
						  $('.doc_canvas_box').css({"position":"relative","overflow":"hidden"});
						//   let distance = dom.getBoundingClientRect(); // 获取元素距离视图上下左右的距离
						  $(dom).css({'position':'absolute','left':(ui.position.left - that.endData.left ),'top':(ui.position.top - that.endData.top -60)})
						  if($(dom).text() != ''){
							  let input = {}
							  input.id = $(dom).attr('id');//1function标识为动态时间
                  			  input.text = $(dom).text().trim()
                  			  input.color = $(dom).css('color')
                  			  Bus.$emit('isInput', input)//组件为文本标识
							  $(dom).appendTo(".doc_canvas_cont").draggable().addClass('selected_dom')
						  }else{
							$(dom).appendTo(".doc_canvas_cont").draggable().resizable({
							  aspectRatio: true,
						  	  handles: "n, e, s, w, ne, se, sw, nw" ,
							  disabled: false,
							  start:function(e,ui){
							},
							  stop: function (e,ui) {
							  }}).addClass('selected_dom')
							$(".selected_dom").children(".xzIcon").css("visibility","visible");
						  }
					}
        		    
				  }}
        		)
			}else{
				$(this).draggable({disabled: true})
			}
		})
		$('.doc_canvas_cont').on('click','.svgBody',function(){
			if(that.isitemBtnsI == '1'){
				$(".xzIcon").css("visibility","hidden");
				$(".svgBody").draggable({ disabled: true }).removeClass('selected_dom').resizable({ disabled: true })
				$(".svgBody").children(".ui-resizable-handle").css("display", "none");
				// console.log($(this).text());
				if($(this).text() != ''){
					$(this).draggable().addClass('selected_dom')
				}else{
					$(this).draggable().resizable({aspectRatio: true, disabled:false, handles: "n, e, s, w, ne, se, sw, nw" } ).addClass('selected_dom')
					// console.log($(".selected_dom").children(".xzIcon"));
				}
				$(".selected_dom").children(".xzIcon").css("visibility","visible");
				let e = {}
				e.id = $(this).attr('id');
                e.text = $(this).text()
                e.color = $(this).css('color')
                Bus.$emit('isInput',e)//组件为文本标识
			}
		})

		// 阻止右击默认事件
		document.oncontextmenu=function(){
            return false;
        }

		$('.doc_canvas_cont').on('mousedown',function(g){
			that.delDom = g.target;
        	var key= g.which;//获取鼠标键位
        	if(key==3){//1：代表左键；2：代表中键；3：代表右键
        	    //获取右键点击坐标
        	    var x=g.clientX;
        	    var y=g.clientY;
        	    $('.menu').show().css({left:x,top:y});
        	}
        })

		$('.doc_canvas_box').on('click',function(){
        	$('.menu').hide();
        })
	},
    methods:{
		//组件旋转
		getDragAngle(event) {
    	  var element = event.target;
    	  var startAngle = parseFloat(element.dataset.angle) || 0;
    	  var center = {
    	    x: parseFloat(element.dataset.centerX) || 0,
    	    y: parseFloat(element.dataset.centerY) || 0,
    	  };
    	  var angle = Math.atan2(center.y - event.clientY, center.x - event.clientX);
    	  return angle - startAngle;
    	},
		delAllDrag(){
			//组件失焦取消控制框
			$('.doc_canvas_cont').children(".svgBody").resizable({disabled: true }).removeClass('selected_dom')
        	$('.doc_canvas_cont').children(".svgBody").children(".ui-resizable-handle").css("display", "none");
			$(".xzIcon").css("visibility","hidden");
		},
		takeScreenshot() {
		  	// html2canvas(document.querySelector('.doc_canvas_box')).then(canvas => {
			//     var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
            //     window.location.href = imgUri; // 下载图片
			// });
			let x = $('.doc_canvas_cont').children("div")
			$('.doc_canvas_cont').each(function(index,ele){
				$(this)[0].childNodes.forEach(item =>{
					console.log(item.getBoundingClientRect());
				})
  			});
		},
		end(e){
			if(e){
				this.endData = e
			}
		},
    	rightDel(){
			let data = $(this.delDom).attr('id')
			Bus.$emit('delDom',data)
    	  	$(this.delDom).remove()
		  	$('.menu').hide();
    	},
		//置顶置底
		rightTop(){
			let z = $(this.delDom).css('z-index')
			if(z != 'auto'){
				this.maxZ = this.maxZ +1
				$(this.delDom).css('z-index', this.maxZ)
			}else{
				$(this.delDom).css('z-index', '1')
			}
		  	$('.menu').hide();
		},
		rightDown(){
			let z = $(this.delDom).css('z-index')
			if(z != 'auto'){
				this.minZ = this.minZ - 1
				$(this.delDom).css('z-index', this.minZ)
			}else{
				$(this.delDom).css('z-index', '-1')
			}
		  	$('.menu').hide();
		},
		itemBtnsI(e){
			this.isitemBtnsI = e
			console.log(this.isitemBtnsI,'huabu');
			if(this.isitemBtnsI == '2'){
				$('.doc_canvas_cont').children(".svgBody").resizable({disabled: true }).removeClass('selected_dom')
				$('.doc_canvas_cont').children(".svgBody").children(".ui-resizable-handle").css("display", "none");
			}
		},
        close(e){
			if(e == false){
				this.formData = {}
				this.dialogVisible = false
			}
		},
        save(flag){
		},
        
    }
}
</script>

<style scoped>
.pc_left .el-menu{
	height: 245px !important;
	border:none
}
</style>
<style scoped="scoped" lang="scss">
.menu{
	position:absolute;
    display: flex;
	flex-direction: column;
	border: 1px solid rgb(129, 129, 129);
	div{
		text-align: center;
		line-height: 30px;
		border-bottom: 1px solid rgb(194, 191, 191);
		width: 90px;
		height: 30px;
		background: rgb(255, 255, 255);
	}
	div:hover{
		background: rgb(238, 238, 238);
		cursor: pointer;
	}
}
.doc_canvas_cont{
	position: relative;
	
}
.pc_left{
	z-index: 2999 !important;
	width:299px;
	position: fixed;
	background: #fff;
	border-right: solid 1px #e6e6e6;;

}

.pc_head {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background-color: #383e41;
    text-align: center;
    z-index: 3000;

    .click_select{
        display: inline-block;
        max-width: 300px;
        height: 60px;
        line-height: 60px;
        color: #fff;
        font-size: 16px;
    }

    .head_btn{
        position: relative;
        float: right;
        margin-right: 20px;
        span{
            position: relative;
            float: right;
            height: 60px;
            line-height: 60px;
            padding: 0 5px;
            color: #fff;
            font-size: 14px;
            cursor: pointer;
            i{
                margin-right: 5px;
				
            }
        }
    }
}


	
	
</style>